import { defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { fileURLToPath } from 'url'

// element-plus按需引入配置
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import ElementPlus from 'unplugin-element-plus/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
// electron
import electron from 'vite-plugin-electron'
import electronRenderer from 'vite-plugin-electron-renderer'
import { viteMockServe } from 'vite-plugin-mock'
// mock

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
	const root = process.cwd()
	const env = loadEnv(mode, root)
	console.log(env)
	return {
		// 获取当前工作目录
		plugins: [
			vue({
				template: {
					compilerOptions: { isCustomElement: (tag) => tag === 'webview' } // 不让vue解析webview标签
				}
			}),
			viteMockServe({
				mockPath: 'mock',
				enable: true
			}),
			ElementPlus({}),
			AutoImport({
				// 				// 自动引入ref,reactive等vue3的api
				imports: ['vue', 'vue-router', 'pinia'],
				eslintrc: {
					enabled: true
				},
				resolvers: [
					ElementPlusResolver(), // 自动导入图标组件
					IconsResolver({
						prefix: 'Icon'
					})
				],
				dts: fileURLToPath(new URL('./types/auto-imports.d.ts', import.meta.url))
			}),
			Components({
				resolvers: [
					ElementPlusResolver(), // 自动注册图标组件
					IconsResolver({
						enabledCollections: ['ep']
					})
				],
				dts: fileURLToPath(new URL('./types/components.d.ts', import.meta.url)),
				dirs: [fileURLToPath(new URL('./src/components', import.meta.url))]
			}),
			// 自动安装图标
			Icons({
				autoInstall: true
			}),
			electron({
				entry: 'electron/index.ts' // 主进程文件
			}),
			electronRenderer()
		],
		server: {
			port: 5173, // 端口号
			cors: true,
			proxy: {
				[env.VITE_APP_MOCK_BASEURL]: {
					target: 'http://localhost:9000',
					// 改变 Host Header
					changeOrigin: true
				}
			}
		},
		base: '/',
		resolve: {
			alias: {
				'@': path.resolve(__dirname, 'src')
			}
		},
		build: {
			emptyOutDir: false // 默认情况下，若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录
		},
		worker: {
			format: 'es'
		}
	}
})
